<template>
  <div class="customer-page">
    <!-- 购物车图标：容器大小不变，图标占50% -->
    <div class="cart-icon" ref="cartIcon">
      <el-badge :value="totalCartCount" :max="99">
        <el-button 
          type="primary" 
          @click="goToCartPage"
          class="cart-fab"
        >
          <!-- 给图标添加专属类名，用于控制尺寸 -->
          <el-icon class="cart-icon-inner">
            <ShoppingCart />
          </el-icon>
        </el-button>
      </el-badge>
    </div>

    <!-- 分类导航 -->
    <el-tabs v-model="activeCategory" type="border-card" @tab-change="filterMenu">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane
        v-for="c in categories"
        :key="c"
        :label="c"
        :name="c"
      ></el-tab-pane>
    </el-tabs>

    <!-- 菜品列表 -->
    <el-row :gutter="20">
      <transition-group name="list-fade" tag="div" class="menu-grid">
        <el-col :xs="12" :sm="8" :md="6" v-for="item in filteredItems" :key="item.foodId">
          <el-card shadow="hover" class="menu-card">
            <!-- 已下架标签 -->
            <el-tag v-if="item.foodStatus === 'notsale'" type="danger" class="sold-out">已下架</el-tag>

            <el-image
              :src="`/images/${item.foodImg || 'default'}.jpg`"
              fit="cover"
              lazy
              class="menu-img"
              :class="{ 'sold-out-img': item.foodStatus === 'notsale' }"
              :alt="item.foodName"
            >
              <template #placeholder>
                <div class="image-loading">加载中...</div>
              </template>
              <template #error>
                <img src="/images/baicai.jpg" alt="默认图片" class="menu-img" />
              </template>
            </el-image>

            <h3>{{ item.foodName }}</h3>
            <p>{{ item.foodPrice }} 元</p>
            <p class="sales">本月销量：{{ item.monthlySales || 0 }}</p>

            <!-- 加入购物车 / 数量控制器 -->
            <template v-if="item.foodStatus === 'onsale'">
              <transition name="fade" mode="out-in">
                <el-button
                  v-if="getCartCount(item.foodId) === 0"
                  key="add-button"
                  type="primary"
                  @click="addOne(item, $event)"
                >
                  加入购物车
                </el-button>
                
                <el-input-number
                  v-else
                  key="input-number"
                  v-model="cartCount[item.foodId]"
                  :min="0"
                  :step="1"
                  size="small"
                  @change="val => handleCountChange(item, val)"
                  class="custom-input-number"
                ></el-input-number>
              </transition>
            </template>

            <!-- 已下架按钮 -->
            <el-button 
              v-else 
              type="info" 
              disabled 
              class="disabled-btn"
            >
              已下架
            </el-button>
          </el-card>
        </el-col>
      </transition-group>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'
import { get } from '../utils/axios.js'

// 路由实例
const router = useRouter()

// 状态管理
const menuItems = ref([])
const filteredItems = ref([])
const categories = ref([])
const activeCategory = ref('all')
const cartCount = ref({})
const monthlySales = ref({})  
const cartIcon = ref(null)

// 计算购物车总数量
const totalCartCount = computed(() => 
  Object.values(cartCount.value).reduce((sum, count) => sum + count, 0)
)

let refreshTimer = null  // 定时器

/* 购物车跳转 */
function goToCartPage() {
  router.push('/cart').catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      ElMessage.error('购物车页面不存在，请检查路由配置')
    }
  })
}

/* 获取菜品列表 */
async function fetchMenu() {
  try {
    const [res, sales] = await Promise.all([
      get('/food/menuAll'),
      get('/food/monthlySales')
    ])
    menuItems.value = res || []  // 确保是数组，避免undefined
    monthlySales.value = sales || {}

    menuItems.value.forEach(item => {
      item.monthlySales = monthlySales.value[item.foodName] || 0
    })

    categories.value = [...new Set(res.map(i => i.foodCategory))]
    filterMenu()
  } catch (err) {
    console.error('加载菜单失败:', err)
    ElMessage.error('加载菜单失败，请稍后重试')
    // 出错时显示空列表，避免渲染错误
    menuItems.value = []
    filteredItems.value = []
    categories.value = []
  }
}

/* 分类筛选 */
function filterMenu() {
  if (activeCategory.value === 'all') {
    filteredItems.value = menuItems.value
  } else {
    filteredItems.value = menuItems.value.filter(
      i => i.foodCategory === activeCategory.value
    )
  }
}

/* 购物车逻辑 */
function getCartCount(id) {
  return cartCount.value[id] || 0
}

function addOne(item, event) {
  if (item.foodStatus !== 'onsale') {
    ElMessage.warning('该商品已下架，无法加入购物车')
    return
  }
  cartCount.value[item.foodId] = 1
  syncStorage()
  ElMessage.success('已加入购物车')

  // 飞入动画（增加安全判断）
  if (!event || !event.target) return
  const card = event.target.closest('.menu-card')
  if (!card) return
  const originImg = card.querySelector('.menu-img')
  if (!originImg || !cartIcon.value) return

  const clone = originImg.cloneNode(true)
  const rect = originImg.getBoundingClientRect()

  clone.style.position = 'fixed'
  clone.style.left = `${rect.left}px`
  clone.style.top = `${rect.top}px`
  clone.style.width = `${rect.width}px`
  clone.style.height = `${rect.height}px`
  clone.style.zIndex = '9999'
  clone.style.transition = 'all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
  clone.style.pointerEvents = 'none'

  document.body.appendChild(clone)

  const cartRect = cartIcon.value.getBoundingClientRect()

  setTimeout(() => {
    if (clone.parentNode) {  // 检查元素是否仍存在
      clone.style.left = `${cartRect.left + (cartRect.width / 2) - 10}px`
      clone.style.top = `${cartRect.top + (cartRect.height / 2) - 10}px`
      clone.style.width = '20px'
      clone.style.height = '20px'
      clone.style.opacity = '0.5'
      clone.style.transform = 'rotate(360deg)'
    }
  }, 50)

  setTimeout(() => {
    if (clone.parentNode) clone.remove()
  }, 850)
}

function handleCountChange(item, val) {
  if (item.foodStatus !== 'onsale') {
    ElMessage.warning('该商品已下架，无法修改数量')
    return
  }
  const id = item.foodId
  if (val === 0) {
    delete cartCount.value[id]
  } else {
    cartCount.value[id] = val
  }
  syncStorage()
}

function syncStorage() {
  try {
    const arr = Object.entries(cartCount.value).map(([foodId, quantity]) => ({
      foodId: Number(foodId),
      foodName: menuItems.value.find(i => i.foodId === Number(foodId))?.foodName || '',
      foodPrice: menuItems.value.find(i => i.foodId === Number(foodId))?.foodPrice || 0,
      quantity
    }))
    localStorage.setItem('cart', JSON.stringify(arr))
  } catch (err) {
    console.error('同步购物车失败:', err)
  }
}

/* 初始化 */
onMounted(() => {
  fetchMenu()

  try {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]')
    cart.forEach(item => {
      cartCount.value[item.foodId] = item.quantity
    })
  } catch (err) {
    console.error('解析购物车数据失败:', err)
    localStorage.removeItem('cart')  // 清除损坏的购物车数据
  }

  // 每5分钟自动刷新菜单
  refreshTimer = setInterval(async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '菜单正在刷新...',
      background: 'rgba(0, 0, 0, 0.3)'
    })
    try {
      await fetchMenu()
      ElMessage.success('菜单已刷新')
    } catch (err) {
      ElMessage.error('菜单刷新失败')
    } finally {
      loading.close()
    }
  }, 300000)
})

/* 页面卸载 */
onBeforeUnmount(() => {
  if (refreshTimer) clearInterval(refreshTimer)
})
</script>

<style scoped>
.customer-page {
  padding: 20px;
  position: relative;
}

/* 购物车图标容器：位置不变 */
.cart-icon {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
}

/* 正圆购物车按钮：容器大小保持不变（桌面64px，移动端56px） */
.cart-fab {
  width: 64px !important;  /* 容器宽度不变 */
  height: 64px !important; /* 容器高度不变 */
  min-width: unset !important;
  padding: 0 !important;
  border-radius: 50% !important;
  display: flex;
  align-items: center;  /* 确保图标垂直居中 */
  justify-content: center; /* 确保图标水平居中 */
  box-shadow: 0 6px 12px rgba(255, 87, 34, 0.3);
  transition: all 0.3s ease;
}
.cart-fab:hover {
  transform: scale(1.12);
  box-shadow: 0 8px 16px rgba(255, 87, 34, 0.4);
}

/* 核心修改：购物车图标占按钮50%大小 */
.cart-icon-inner {
  /* 桌面端：按钮64px × 50% = 32px */
  font-size: 32px !important; 
  /* 强化图标自身居中（避免偏移） */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 小屏适配：容器56px × 50% = 28px */
@media (max-width: 768px) {
  .cart-fab {
    width: 56px !important;  /* 移动端容器大小不变 */
    height: 56px !important;
  }
  .cart-icon-inner {
    font-size: 28px !important; /* 移动端图标占50% */
  }
}

/* 菜品列表样式（无修改） */
.menu-grid {
  display: flex;
  flex-wrap: wrap;
  margin: -10px;
}
.menu-grid .el-col {
  padding: 10px;
}
.menu-card {
  text-align: center;
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.menu-card:hover {
  transform: scale(1.02);
}
.menu-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px 4px 0 0;
}
.image-loading {
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
}
.sold-out-img {
  filter: grayscale(100%);
  opacity: 0.7;
}
.sold-out {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
}
h3 {
  margin: 10px 0 5px;
}
p {
  margin: 5px 0;
}
.sales {
  color: #888;
  font-size: 12px;
}
.el-button {
  margin-top: auto;
  width: 100%;
}
.disabled-btn {
  width: 100%;
  margin-top: auto;
}

/* 数量控制器样式（无修改） */
.custom-input-number {
  width: 100%;
  height: 40px;
}
:deep(.custom-input-number) .el-input-number__decrease,
:deep(.custom-input-number) .el-input-number__increase {
  width: 40px;
  height: 100%;
  font-size: 18px;
}
:deep(.custom-input-number) .el-input-number__input {
  width: calc(100% - 80px);
  height: 100%;
  font-size: 16px;
  text-align: center;
}
:deep(.custom-input-number) .el-input-number__decrease:hover,
:deep(.custom-input-number) .el-input-number__increase:hover {
  background-color: #fff3e0;
  color: #ff5722;
}

/* 过渡动画（无修改） */
.list-fade-enter-active,
.list-fade-leave-active {
  transition: all 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.list-fade-enter-from,
.list-fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
.list-fade-move {
  transition: transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式适配（无修改） */
@media (max-width: 768px) {
  .custom-input-number {
    height: 36px;
  }
  :deep(.custom-input-number) .el-input-number__decrease,
  :deep(.custom-input-number) .el-input-number__increase {
    width: 36px;
    font-size: 16px;
  }
  :deep(.custom-input-number) .el-input-number__input {
    width: calc(100% - 72px);
    font-size: 14px;
  }
}
</style>